<template>
    <div id="MemberCard">
        <div>
            <el-card class="box-card">
                <el-row>
                <el-col :span="8">
                    <el-input
                    placeholder="请输入会员类型"
                    v-model="memberName"
                    clearable>
                    </el-input>
                </el-col>
                <el-col :span="2" :offset="1"><el-button icon="el-icon-search" @click="getMemberTypeByPage" circle></el-button></el-col>
                <el-col :span="2"><el-button type="primary" @click="addMemberType" round>新增</el-button></el-col>
                </el-row>
                <el-row :gutter="20" style="margin-top:30px;">
                    <el-col :span="24">
                        <el-table
                            :data="productData"
                            border
                            style="width:100%">
                            <el-table-column
                            fixed
                            prop="id"
                            label="序号"
                            >
                            </el-table-column>
                            <el-table-column
                            prop="memberName"
                            label="会员类型"
                            >
                            </el-table-column>
                            <el-table-column
                            fixed="right"
                            label="操作"
                            width="200">
                            <template slot-scope="scope">
                                <el-button @click="handleUpdate(scope.row)" type="text" size="small">编辑</el-button>
                                <el-button @click="deleteMemberType(scope.row)" type="text" size="small" style="color: red;">删除</el-button>
                            </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row style="text-align: center;">
                    <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage4"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="page.total">
                </el-pagination>
                </el-row>
            </el-card>
            <!-- 数据新增功能 -->
            <el-dialog title="新增会员卡" :visible.sync="dialogFormVisible" @close="handleClose('productForm')">
            <el-form :model="productForm" :rules="rules" ref="productForm">
                <el-form-item label="会员类型" :label-width="formLabelWidth" prop="memberName">
                    <el-input v-model="productForm.memberName" autocomplete="off" ></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveCard('productForm')">确 定</el-button>
            </div>
            </el-dialog>
            <!-- 数据修改功能 -->
            <el-dialog title="会员卡编辑" :visible.sync="dialogFormVisibleUpdate" @close="handleClose('productFormEdit')">
                <el-form :model="productFormEdit" :rules="rules" ref="productFormEdit">
                    <el-form-item label="会员卡名称" :label-width="formLabelWidth" prop="memberName">
                        <el-input v-model="productFormEdit.memberName" autocomplete="off"  @input="changeMessage($event)"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisibleUpdate = false">取 消</el-button>
                    <el-button type="primary" @click="updateMemberType('productFormEdit')">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
const axios = require('axios')
export default {
  name: 'memberType',
  data () {
    // 校验新增修改中会员名称是否为空或者名称是否正确或者是否重复
    const memberName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入会员卡名称'))
      } else if (value === this.checkMemberName) {
        callback()
      } else {
        const a = window.sessionStorage.getItem('token')
        this.$axios.get('http://127.0.0.1:15000/eat-service/memberType/checkMembertypeName?memberName=' + value).then(res => {
          if (res.data.obj != null) {
            callback(new Error('该会员名称已录入'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      updateCardName: '',
      imageUrl: '',
      imageFile: File,
      // 分页模糊查查询字段（会员卡名称）
      memberName: '',
      // 分页全查存放的数组
      productData: [],
      // 新增弹框true弹出
      dialogFormVisible: false,
      // 查看弹框true弹出
      dialogFormVisibleDatil: false,
      // 修改弹框true弹出
      dialogFormVisibleUpdate: false,
      // 新增时使用到的form对象
      productForm: {
        id: '',
        // 会员卡名称
        memberName: ''
      },
      // 修改时使用到的form对象
      productFormEdit: {
        id: '',
        // 会员卡名称
        memberName: ''
      },
      formLabelWidth: '120px',
      // 分页当前选中页
      currentPage4: 1,
      page: {
        pageSize: 10, // 条数
        pageNum: 1, // 页数
        total: 0
      },
      tatal: 0,
      // 新增校验规则
      rules: {
        memberName: [
          { validator: memberName, trigger: 'blur' }
        ]
      },
      // 修改校验会员名称
      checkMemberName: ''
    }
  },
  methods: {
    // 强制更新修改会员名称输入框的值
    // 用于无法删除输入框值的时候
    changeMessage () {
      this.$forceUpdate()
    },
    // 新增修改清空值
    handleClose (formName) {
      this.$refs[formName].resetFields()// 重置数据，同时也取消了表单的校验 refundFormData：el-form用ref绑定的值，
    },
    handleRemove (file, fileList) {
      console.log(file, fileList)
    },
    handlePreview (file) {
      console.log(file)
    },
    // 分页
    handleSizeChange (ps) {
      this.page.pageSize = ps
      this.getMemberTypeByPage()
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange (pn) {
      this.page.pageNum = pn
      this.getMemberTypeByPage()
    },
    // 会员卡分页查+模糊查（会员卡名称）
    getMemberTypeByPage () {
      this.$axios.get('http://127.0.0.1:15000/eat-service/memberType/getMemberTypeByPage', {
        params: {
          memberName: this.memberName,
          pageSize: this.page.pageSize,
          pageNum: this.page.pageNum
        }
      })
        .then((res) => {
          this.productData = res.data.content
          this.page.total = res.data.total
        })
    },
    // 新增会员卡类型
    saveCard (formName) {
      const formdata = new FormData()
      formdata.set('memberName', this.productForm.memberName)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('http://127.0.0.1:15000/eat-service/memberType/saveMemberType', formdata)
            .then(res => {
              if (res.data.obj > 0) {
                this.message('恭喜你，保存数据成功！', 'success')
                this.dialogFormVisible = false
                this.productForm = {
                  // 会员名称
                  memberName: ''
                }
                this.getMemberTypeByPage()
              } else {
                this.message('对不起，保存失败！', 'warning')
              }
            }).catch(error => {
              this.$message.error('服务器崩溃了，请稍后再尝试使用！')
            })
        } else {
          return false
        }
      })
    },
    // 修改会员卡类型
    updateMemberType (formName) {
      const formdata = new FormData()
      formdata.set('id', this.productFormEdit.id)
      formdata.set('memberName', this.productFormEdit.memberName)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.put('http://127.0.0.1:15000/eat-service/memberType/updateMemberType', formdata)
            .then(res => {
              if (res.data.code === '200') {
                this.message('恭喜你，修改数据成功！', 'success')
                this.dialogFormVisibleUpdate = false
                this.imageUrl = ''
                this.imageFile = File
                this.productFormEdit = {
                  memberName: '' // 会员名称
                }
                this.getMemberTypeByPage()// 重新渲染数据列表
              } else {
                this.message('对不起，修改失败！', 'warning')
              }
            }).catch(error => {
              this.$message.error('服务器崩溃了，请稍后再尝试使用！')
            })
        }
      })
    },
    // 删除会员卡类型
    deleteMemberType (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }// 删除提示框
      ).then(() => {
        this.$axios.delete('http://127.0.0.1:15000/eat-service/memberType/deleteMemberType?id=' + row.id)
          .then(res => {
            if (res.data.code === '200') {
              this.message('恭喜你，删除成功！', 'success')
              this.getMemberTypeByPage()
            } else {
              this.message('删除失败', 'warning')
            }
          }).catch(error => {
            alert(error)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 消息提示框
    message (message, type) {
      this.$message({
        message: message,
        type: type
      })
    },
    // 修改按钮回显值
    handleUpdate (row) {
      this.dialogFormVisibleUpdate = true
      this.productFormEdit.id = row.id
      this.productFormEdit.memberName = row.memberName
      this.checkMemberName = row.memberName
    },
    // 新增按钮弹出弹框
    addMemberType () {
      this.dialogFormVisible = true
    }
  },
  // 初始化加载数据
  mounted () {
    // 分页全查+模糊查（会员名称）
    this.getMemberTypeByPage()
  }
}
</script>
<style>
</style>
